import axios from "axios";
import {ElMessage} from "element-plus";
import 'element-plus/theme-chalk/el-message.css'

const admin_service = axios.create({
    // baseURL: "http://localhost:8081/v2",
    baseURL: "/v2",
})

// 请求前拦截
admin_service.interceptors.request.use(
    config => {
        const token = localStorage.getItem("token")
        const username = localStorage.getItem("username")
        if (token) {
            config.headers["token"] = token
            config.headers["username"] = username
        } else {
            ElMessage.error("请登录！")
            window.location.href = '/#/login'
        }
        return config
    },
    error => {
        console.log(error)
    }
)

// 响应拦截
admin_service.interceptors.response.use(
    response => {
        return response
    }, error => {
        if (error.response.status === 400) {
            window.localStorage.removeItem('token')
            window.localStorage.removeItem('username')
            ElMessage.error("登录失效！")
            window.location.href = '/#/login'
        } else {
            ElMessage.error(`系統异常：${error.response.status}`)
        }
    }
)

let admin = {}
admin.auth = () => {
    return admin_service({
        url: '/auth',
        method: 'post'
    })
}

admin.addSort = (data) => {
    return admin_service({
        url: '/addSort',
        data,
        method: 'post'
    })
}

admin.getSorts = () => {
    return admin_service({
        url: '/getSorts',
        method: 'get'
    })
}

admin.deleteSort = (data) => {
    return admin_service({
        url: '/deleteSort',
        data,
        method: 'post'
    })
}

admin.sortMenu = (data) => {
    return admin_service({
        url: '/sortMenu',
        data,
        method: 'post'
    })
}

admin.releaseArticle = (data) => {
    return admin_service({
        url: '/releaseArticle',
        data,
        method: 'post'
    })
}

admin.getArticleList = () => {
    return admin_service({
        url: '/getArticleList',
        method: 'get'
    })
}

admin.pagingFind = (data) => {
    return admin_service({
        url: '/pagingFind',
        data,
        method: 'post'
    })
}

admin.deleteArticle = (data)=>{
    return admin_service({
        url: '/deleteArticle',
        data,
        method: 'post'
    })
}

admin.findArticleInfo = (data)=>{
    return admin_service({
        url: '/findArticleInfo',
        data,
        method: 'post'
    })
}

admin.updateArticle = (data) =>{
    return admin_service({
        url: '/updateArticle',
        data,
        method: 'post'
    })
}

export default admin